//
//  TMessageController.m
//  UIKit
//
//  Created by kennethmiao on 2018/9/18.
//  Copyright © 2018年 kennethmiao. All rights reserved.
//

#import "TMessageController.h"
#import "TTextMessageCell.h"
#import "TSystemMessageCell.h"
#import "TVoiceMessageCell.h"
#import "TImageMessageCell.h"
#import "TLocationCell.h"
#import "TGoodsCell.h"
#import "TFaceMessageCell.h"
#import "TVideoMessageCell.h"
#import "TFileMessageCell.h"
#import "TUIKitConfig.h"
#import "TFaceView.h"
#import "THeader.h"
#import "TUIKit.h"
#import "THelper.h"
#import "TGiftMessageCell.h"
#import "TCallCell.h"
#import <AVFoundation/AVFoundation.h>
#import "EMVoiceConverter.h"
#import "TChatAlertView.h"
#import "YBCenterVC.h"
typedef void (^IMMArrayBlock)(NSArray *transformArray);

@interface TMessageController () <TMessageCellDelegate, AVAudioPlayerDelegate,V2TIMAdvancedMsgListener>{
    TChatAlertView *chatalertview;
    dispatch_group_t _rk_group;
}
@property (nonatomic, strong) TConversationCellData *conv;
@property (nonatomic, strong) NSMutableArray *uiMsgs;
@property (nonatomic, strong) NSMutableArray *heightCache;
@property (nonatomic, strong) V2TIMMessage *lastMsg;
@property (nonatomic, strong) V2TIMMessage *msgForDate;
@property (nonatomic, strong) TMessageCellData *menuUIMsg;
@property (nonatomic, strong) TMessageCellData *reSendUIMsg;
@property (nonatomic, strong) UIActivityIndicatorView *headerView;
@property (nonatomic, assign) BOOL isScrollBottom;
@property (nonatomic, assign) BOOL isLoadingMsg;
@property (nonatomic, assign) BOOL noMoreMsg;
@property (nonatomic, strong) AVAudioPlayer *voicePlayer;
@end

@implementation TMessageController

- (void)viewDidLoad
{
    [super viewDidLoad];
    _rk_group = dispatch_group_create();
    [self setupViews];
}


- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewWillAppear:(BOOL)animated
{
    [self readedReport];
    [super viewWillAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [self readedReport];
    [super viewWillDisappear:animated];
}

- (void)readedReport{
    [[YBImManager shareInstance]clearUnreadConvId:_conv.convId sendNot:NO];
}

- (void)setupViews {
    [[V2TIMManager sharedInstance] addAdvancedMsgListener:self];

//    NSNotificationCenter *notiCenter = [NSNotificationCenter defaultCenter];
//    [notiCenter addObserver:self selector:@selector(onNewMessage:) name:ybImNeedRefresh object:nil];
//    [notiCenter addObserver:self selector:@selector(onNewMessage:) name:TUIKitNotification_TIMMessageListener object:nil];
//    [notiCenter addObserver:self selector:@selector(onRevokeMessage:) name:TUIKitNotification_TIMMessageRevokeListener object:nil];
//    [notiCenter addObserver:self selector:@selector(onUploadMessage:) name:TUIKitNotification_TIMUploadProgressListener object:nil];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTapViewController)];
    [self.view addGestureRecognizer:tap];
    self.tableView.estimatedRowHeight = 0;
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    //self.tableView.backgroundColor = TMessageController_Background_Color;
    
    _headerView = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, TMessageController_Header_Height)];
    _headerView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
    self.tableView.tableHeaderView = _headerView;
    
    _heightCache = [NSMutableArray array];
    _uiMsgs = [[NSMutableArray alloc] init];
    
}

- (void)setConversation:(TConversationCellData *)conversation
{
    _conv = conversation;
    [self loadMessage];
}
-(void)onRecvMessageRevoked:(NSString *)msgID
{
    TMessageCellData *uiMsg = nil;
    for (uiMsg in _uiMsgs) {
        V2TIMMessage *imMsg = uiMsg.custom;
        
        if(imMsg){
            if([imMsg.msgID isEqual:msgID]){
                __weak typeof(self) ws = self;
                dispatch_async(dispatch_get_main_queue(), ^{
                    [ws revokeMsg:uiMsg];
                });
                break;
            }
        }
    }
}

-(void)onRecvNewMessage:(V2TIMMessage *)msg
{
    if([msg.sender isEqual:_conv.convId]){
        NSLog(@"------收到新消息---%@",msg);
        [[YBImManager shareInstance]onRecvNewMessage:msg complete:^(TMessageCellData *receData) {
                    if(receData){
                        receData.isSelf = msg.isSelf;
    //                    receData.msgUiType = _msgUiType;
                        receData.senderUid = msg.sender;
                        receData.head = TUIKitResource(@"default_head");
                        //data.name = msg.sender;
                        /*
                        if([[msg getConversation] getType] == TIM_GROUP){
                            data.name = [msg getSenderGroupMemberProfile].nameCard;
                        }
                        else if([[msg getConversation] getType] == TIM_C2C){
        //                    data.name = [msg getSenderProfile].nickname;
                            [msg getSenderProfile:^(TIMUserProfile *proflie) {
                                data.name = proflie.nickname;
                            }];
                        }
                        */
                        if(receData.name.length == 0){
                            receData.name = msg.sender;
                        }
                        /*
                        if(msg.status == TIM_MSG_STATUS_SEND_SUCC){
                            data.status = Msg_Status_Succ;
                            [rk_uiMsgs addObject:data];
                        }
                        else if(msg.status == TIM_MSG_STATUS_SEND_FAIL){
                            data.status = Msg_Status_Fail;
                            [rk_uiMsgs addObject:data];
                        }*/
                            receData.userHeader = receData.isSelf ? [Config getUserAvatar] : _conv.userHeader;;
                            receData.name = receData.isSelf ? [Config getOwnNicename] :  _conv.userName;
                            receData.timestamp = msg.timestamp;
                            receData.custom = msg;
                            if(msg.status == V2TIM_MSG_STATUS_SEND_SUCC){
                                receData.status = Msg_Status_Succ;
                                [_uiMsgs addObject:receData];
                            }else if(msg.status == V2TIM_MSG_STATUS_SEND_FAIL){
                                receData.status = Msg_Status_Fail;
                                [_uiMsgs addObject:receData];
                            }
                    }
        }];
        __weak typeof(self) ws = self;
        dispatch_async(dispatch_get_main_queue(), ^{
            [ws.tableView reloadData];
            [ws scrollToBottom:YES];
        });

    }

}

- (void)loadMessage
{
    if(_isLoadingMsg || _noMoreMsg){
        return;
    }
    _isLoadingMsg = YES;
    // 拉取单聊历史消息
    // 首次拉取，lastMsg 设置为 nil
    // 再次拉取时，lastMsg 可以使用返回的消息列表中的最后一条消息
    __weak typeof(self) ws = self;
    [V2TIMManager.sharedInstance getC2CHistoryMessageList:_conv.convId count:20 lastMsg:_lastMsg succ:^(NSArray<V2TIMMessage *> *msgs) {
        // 记录下次拉取的 lastMsg，用于下次拉取
        _lastMsg = msgs.lastObject;
        NSLog(@"success, %@", msgs);
        int msgCount = (int)[[TUIKit sharedInstance] getConfig].msgCountPerRequest;
        [ws transUIMsgFromIMMsg:msgs complete:^(NSArray *transformArray) {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSMutableArray *uiMsgs = [NSMutableArray arrayWithArray:transformArray];
                if(msgs.count < msgCount){
                    ws.noMoreMsg = YES;
                    CGRect frame = ws.headerView.frame;
                    frame.size.height = 0;
                    ws.headerView.frame = frame;
                }
                if(uiMsgs.count != 0){
                    BOOL firstLoad = YES;
                    if(ws.uiMsgs.count != 0){
                        firstLoad = NO;
                    }
                    NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, uiMsgs.count)];
                    [ws.uiMsgs insertObjects:uiMsgs atIndexes:indexSet];
                    [ws.heightCache removeAllObjects];
                    [ws.tableView reloadData];
                    [ws.tableView layoutIfNeeded];
                    if(!firstLoad){
                        CGFloat visibleHeight = 0;
                        for (NSInteger i = 0; i < uiMsgs.count; ++i) {
                            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
                            visibleHeight += [ws tableView:ws.tableView heightForRowAtIndexPath:indexPath];
                        }
                        if(ws.noMoreMsg){
                            visibleHeight -= TMessageController_Header_Height;
                        }
                        [ws.tableView scrollRectToVisible:CGRectMake(0, ws.tableView.contentOffset.y + visibleHeight, ws.tableView.frame.size.width, ws.tableView.frame.size.height) animated:NO];
                    }
                }
                ws.isLoadingMsg = NO;
                [ws.headerView stopAnimating];
            });
        }];

        
    } fail:^(int code, NSString *desc) {
        NSLog(@"fail, %d, %@", code, desc);
    }];
}


- (void)onNewMessage:(NSNotification *)notification {
    NSArray *msgs = notification.object;
    //NSMutableArray *uiMsgs = [self transUIMsgFromIMMsg:msgs];
    [self transUIMsgFromIMMsg:msgs complete:^(NSArray *transformArray) {
        NSMutableArray *uiMsgs = [NSMutableArray arrayWithArray:transformArray];
        [_uiMsgs addObjectsFromArray:uiMsgs];
        __weak typeof(self) ws = self;
        dispatch_async(dispatch_get_main_queue(), ^{
            [ws.tableView reloadData];
            [ws scrollToBottom:YES];
        });
    }];
    
}

//- (void)onRevokeMessage:(NSNotification *)notification {
//    TIMMessageLocator *locator = notification.object;
//    TMessageCellData *uiMsg = nil;
//    for (uiMsg in _uiMsgs) {
//        TIMMessage *imMsg = uiMsg.custom;
//
//        if(imMsg){
//            if([imMsg respondsToLocator:locator]){
//                __weak typeof(self) ws = self;
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    [ws revokeMsg:uiMsg];
//                });
//                break;
//            }
//        }
//    }
//}

//- (void)onUploadMessage:(NSNotification *)notification {
//    NSDictionary *dic = notification.object;
//    TIMMessage *msg = [dic objectForKey:@"message"];
//    NSNumber *progress = [dic objectForKey:@"progress"];
//    for (NSInteger i = 0; i < _uiMsgs.count; ++i) {
//        TMessageCellData *uiMsg = _uiMsgs[i];
//        TIMMessage *imMsg = uiMsg.custom;
//        if(imMsg){
//            if([imMsg respondsToLocator:[msg locator]]){
//                __weak typeof(self) ws = self;
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    if([uiMsg isKindOfClass:[TImageMessageCellData class]]){
//                        TImageMessageCellData *data = (TImageMessageCellData *)uiMsg;
//                        data.uploadProgress = progress.intValue;
//                        TImageMessageCell *cell = [ws.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
//                        [cell setData:data];
//                    }
//                    else if([uiMsg isKindOfClass:[TVideoMessageCellData class]]){
//                        TVideoMessageCellData *data = (TVideoMessageCellData *)uiMsg;
//                        data.uploadProgress = progress.intValue;
//                        TVideoMessageCell *cell = [ws.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
//                        [cell setData:data];
//                    }
//                    else if([uiMsg isKindOfClass:[TFileMessageCellData class]]){
//                        TFileMessageCellData *data = (TFileMessageCellData *)uiMsg;
//                        data.uploadProgress = progress.intValue;
//                        TFileMessageCell *cell = [ws.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
//                        [cell setData:data];
//                    }
//                });
//            }
//        }
//    }
//}

- (void)transUIMsgFromIMMsg:(NSArray *)msgs complete:(IMMArrayBlock)imComplete{
    NSMutableArray *rk_uiMsgs = [NSMutableArray array];
    
    dispatch_queue_t rk_queue = dispatch_get_global_queue(0, 0);
    for (NSInteger k = msgs.count - 1; k >= 0; --k) {
        V2TIMMessage *msg = msgs[k];
        V2TIMConversationType imCType = V2TIM_C2C;
        if (_conv.convType == TConv_Type_C2C) {
            imCType = V2TIM_C2C;
        }else if(_conv.convType == TConv_Type_Group){
            imCType = V2TIM_GROUP;
        }
        //清空未读数
        [[YBImManager shareInstance]clearUnreadConvId:_conv.convId sendNot:NO];
        
        if(![msg.userID isEqualToString:_conv.convId]){
            continue;
        }
        if(msg.status == V2TIM_MSG_STATUS_HAS_DELETED){
            continue;
        }
        TMessageCellData *dateMsg = [self transSystemMsgFromDate:msg.timestamp];
        if(dateMsg){
            _msgForDate = msg;
            dateMsg.custom = nil;
            dateMsg.timestamp = msg.timestamp;
            [rk_uiMsgs addObject:dateMsg];
        }
        //rrrrrrrrrr
        if(msg.status == V2TIM_MSG_STATUS_LOCAL_REVOKED){
            if (msg.isSelf) {
                TSystemMessageCellData *revoke = [[TSystemMessageCellData alloc] init];
                revoke.content = YZMsg(@"你撤回了一条消息");
                revoke.custom = msg;
                revoke.timestamp = msg.timestamp;
                [rk_uiMsgs addObject:revoke];
            }else{
                dispatch_group_enter(_rk_group);
                dispatch_group_async(_rk_group, rk_queue, ^{
                     
//                    [[YBImManager shareInstance] transformInfoWithList:@[msg.sender] finish:^(NSString *transformStr) {
                        TSystemMessageCellData *revoke = [[TSystemMessageCellData alloc] init];
                        revoke.content = [NSString stringWithFormat:@"\"%@\"%@",@"对方",YZMsg(@"撤回了一条消息")];
                        revoke.msgUiType = _msgUiType;
                        revoke.custom = msg;
                        revoke.timestamp = msg.timestamp;
                        [rk_uiMsgs addObject:revoke];
                        dispatch_group_leave(_rk_group);
//                    }];
                });
            }
            continue;
        }
        [[YBImManager shareInstance]onRecvNewMessage:msg complete:^(TMessageCellData *receData) {
                    if(receData){
                        receData.isSelf = msg.isSelf;
                        receData.msgUiType = _msgUiType;
                        receData.senderUid = msg.sender;
                        receData.head = TUIKitResource(@"default_head");
                        //data.name = msg.sender;
                        /*
                        if([[msg getConversation] getType] == TIM_GROUP){
                            data.name = [msg getSenderGroupMemberProfile].nameCard;
                        }
                        else if([[msg getConversation] getType] == TIM_C2C){
        //                    data.name = [msg getSenderProfile].nickname;
                            [msg getSenderProfile:^(TIMUserProfile *proflie) {
                                data.name = proflie.nickname;
                            }];
                        }
                        */
                        if(receData.name.length == 0){
                            receData.name = msg.sender;
                        }
                        /*
                        if(msg.status == TIM_MSG_STATUS_SEND_SUCC){
                            data.status = Msg_Status_Succ;
                            [rk_uiMsgs addObject:data];
                        }
                        else if(msg.status == TIM_MSG_STATUS_SEND_FAIL){
                            data.status = Msg_Status_Fail;
                            [rk_uiMsgs addObject:data];
                        }*/
//                        if (receData.isSelf) {
                            receData.userHeader = receData.isSelf ? [Config getUserAvatar] : _conv.userHeader;;
                            receData.name = receData.isSelf ? [Config getOwnNicename] :  _conv.userName;
                            receData.timestamp = msg.timestamp;
                            receData.custom = msg;
                            if(msg.status == V2TIM_MSG_STATUS_SEND_SUCC){
                                receData.status = Msg_Status_Succ;
                                [rk_uiMsgs addObject:receData];
                            }else if(msg.status == V2TIM_MSG_STATUS_SEND_FAIL){
                                receData.status = Msg_Status_Fail;
                                [rk_uiMsgs addObject:receData];
                            }
//                        }
                    }
        }];
    }
    dispatch_group_notify(_rk_group, rk_queue, ^{
        //NSLog(@"Tim-处理完了");
        NSMutableDictionary *sortDic = [NSMutableDictionary dictionary];
        for (TMessageCellData *cellData in rk_uiMsgs) {
            [sortDic setObject:cellData forKey:cellData.timestamp];
        }
        NSArray *sortAllKey = [sortDic allKeys];
        NSArray *sortResult = [sortAllKey sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
            return [obj1 compare:obj2];
        }];
        NSMutableArray *m_array = [NSMutableArray array];
        for (NSString *key in sortResult) {
            [m_array addObject:[sortDic objectForKey:key]];
        }
        NSArray *realArray = [NSArray arrayWithArray:m_array];
        if (imComplete) {
            //NSLog(@"排序:%@==%@",rk_uiMsgs,realArray);
            imComplete(realArray);
        }
    });
    //return rk_uiMsgs;
}
#pragma mark - Table view data source

-(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_isScrollBottom == NO) {
        [self scrollToBottom:NO];
        if (indexPath.row == _uiMsgs.count-1) {
            _isScrollBottom = YES;
        }
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _uiMsgs.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat height = 0;
    if(_heightCache.count > indexPath.row){
        return [_heightCache[indexPath.row] floatValue];
    }
    NSObject *data = _uiMsgs[indexPath.row];
    if([data isKindOfClass:[TTextMessageCellData class]]){
        TTextMessageCellData *text = _uiMsgs[indexPath.row];
        TTextMessageCell *cell = [[TTextMessageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TTextMessageCell_ReuseId];
        TTextMessageCellData *textData = (TTextMessageCellData*)data;
        CGFloat fyHeight = 0;
        if (![PublicObj checkNull:textData.fyStr]) {
            fyHeight = [textData calculationTransStr:textData.fyStr].height +10;
        }
        height = [cell getHeight:text] + fyHeight;
       
    }else if([data isKindOfClass:[TVoiceMessageCellData class]]){
        TVoiceMessageCellData *voice = _uiMsgs[indexPath.row];
        TVoiceMessageCell *cell = [[TVoiceMessageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TVoiceMessageCell_ReuseId];
        height = [cell getHeight:voice];
    }
    else if([data isKindOfClass:[TImageMessageCellData class]]){
        TImageMessageCellData *image = _uiMsgs[indexPath.row];
        TImageMessageCell *cell = [[TImageMessageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TImageMessageCell_ReuseId];
        height = [cell getHeight:image];
    }
    else if([data isKindOfClass:[TSystemMessageCellData class]]){
        TSystemMessageCellData *system = _uiMsgs[indexPath.row];
        TSystemMessageCell *cell = [[TSystemMessageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TSystemMessageCell_ReuseId];
        height = [cell getHeight:system];
        //NSLog(@"获取高度===%f",height);
    }
    else if([data isKindOfClass:[TFaceMessageCellData class]]){
        TFaceMessageCellData *face = _uiMsgs[indexPath.row];
        TFaceMessageCell *cell = [[TFaceMessageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TFaceMessageCell_ReuseId];
        height = [cell getHeight:face];
    }
    else if([data isKindOfClass:[TVideoMessageCellData class]]){
        TVideoMessageCellData *video = _uiMsgs[indexPath.row];
        TVideoMessageCell *cell = [[TVideoMessageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TVideoMessageCell_ReuseId];
        height = [cell getHeight:video];
    }
    else if([data isKindOfClass:[TFileMessageCellData class]]){
        TFileMessageCellData *file = _uiMsgs[indexPath.row];
        TFileMessageCell *cell = [[TFileMessageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TFileMessageCell_ReuseId];
        height = [cell getHeight:file];
    }
    else if([data isKindOfClass:[TGiftMessageCellData class]]){
        height = 86;
    }else if ([data isKindOfClass:[TCallCellData class]]){
        TCallCellData *text = _uiMsgs[indexPath.row];
        TCallCell *cell = [[TCallCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TTextMessageCell_ReuseId];
        height = [cell getHeight:text];
    }else if ([data isKindOfClass:[TLocationCellData class]]){
        TLocationCellData *text = _uiMsgs[indexPath.row];
        TLocationCell *cell = [[TLocationCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TLocationMessageCell_ReuseId];
        height = [cell getHeight:text];
    }else if ([data isKindOfClass:[TGoodsCellData class]]){
        TGoodsCellData *text = _uiMsgs[indexPath.row];
        TGoodsCell *cell = [[TGoodsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TGoodsMessageCell_ReuseId];
        height = [cell getHeight:text];
    }
    [_heightCache insertObject:[NSNumber numberWithFloat:height] atIndex:indexPath.row];
    return height;
}
/// 翻译处理
-(void)insertTrans:(NSString *)trans andIndex:(NSIndexPath *)indexPath {
    dispatch_async(dispatch_get_main_queue(), ^{
        TMessageCellData *data = _uiMsgs[indexPath.row];
        if ([data isKindOfClass:[TTextMessageCellData class]]) {
            TTextMessageCellData *textData = (TTextMessageCellData *)data;
            textData.fyStr = trans;
            textData.transBoxShow = ![PublicObj checkNull:trans];
            textData.fySize = [textData calculationTransStr:trans];
            [_uiMsgs replaceObjectAtIndex:indexPath.row withObject:textData];
            
            // 更新高度
            TTextMessageCellData *text = _uiMsgs[indexPath.row];
            TTextMessageCell *cell = [[TTextMessageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TTextMessageCell_ReuseId];
            CGFloat fyHeight = 0;
            if (![PublicObj checkNull:textData.fyStr]) {
                fyHeight = [textData calculationTransStr:textData.fyStr].height +10;
            }
            CGFloat newHeight = [cell getHeight:text] + fyHeight;
            [_heightCache replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithFloat:newHeight]];
            [self.tableView reloadData];
        }
    });
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TMessageCellData *data = _uiMsgs[indexPath.row];
    TMessageCell *cell = nil;
    if([data isKindOfClass:[TTextMessageCellData class]]){
        cell = [tableView dequeueReusableCellWithIdentifier:TTextMessageCell_ReuseId];
        if(!cell){
            cell = [[TTextMessageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TTextMessageCell_ReuseId];
            cell.delegate = self;
        }
        /// 翻译按钮
        TTextMessageCell *textCell = (TTextMessageCell*)cell;
        YBWeakSelf;
        textCell.transEvent = ^(NSString *trans) {
            [weakSelf insertTrans:trans andIndex:indexPath];
        };
    }
    else if([data isKindOfClass:[TVoiceMessageCellData class]]){
        cell = [tableView dequeueReusableCellWithIdentifier:TVoiceMessageCell_ReuseId];
        if(!cell){
            cell = [[TVoiceMessageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TVoiceMessageCell_ReuseId];
            cell.delegate = self;
        }
    }
    else if([data isKindOfClass:[TImageMessageCellData class]]){
        cell = [tableView dequeueReusableCellWithIdentifier:TImageMessageCell_ReuseId];
        if(!cell){
            cell = [[TImageMessageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TImageMessageCell_ReuseId];
            cell.delegate = self;
        }
    }
    else if([data isKindOfClass:[TSystemMessageCellData class]]){
        cell = [tableView dequeueReusableCellWithIdentifier:TSystemMessageCell_ReuseId];
        if(!cell){
            cell = [[TSystemMessageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TSystemMessageCell_ReuseId];
            cell.delegate = self;
        }
    }
    else if([data isKindOfClass:[TFaceMessageCellData class]]){
        cell = [tableView dequeueReusableCellWithIdentifier:TFaceMessageCell_ReuseId];
        if(!cell){
            cell = [[TFaceMessageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TFaceMessageCell_ReuseId];
            cell.delegate = self;
        }
    }
    else if([data isKindOfClass:[TVideoMessageCellData class]]){
        cell = [tableView dequeueReusableCellWithIdentifier:TVideoMessageCell_ReuseId];
        if(!cell){
            cell = [[TVideoMessageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TVideoMessageCell_ReuseId];
            cell.delegate = self;
        }
    }
    else if([data isKindOfClass:[TFileMessageCellData class]]){
        cell = [tableView dequeueReusableCellWithIdentifier:TFileMessageCell_ReuseId];
        if(!cell){
            cell = [[TFileMessageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TFileMessageCell_ReuseId];
            cell.delegate = self;
        }
    }
    else if([data isKindOfClass:[TGiftMessageCellData class]]){
        cell = [tableView dequeueReusableCellWithIdentifier:TGiftMessageCell_ReuseId];
        if(!cell){
            cell = [[TGiftMessageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TGiftMessageCell_ReuseId];
            cell.delegate = self;
        }
    }
    else if([data isKindOfClass:[TCallCellData class]]){
        cell = [tableView dequeueReusableCellWithIdentifier:TCallMessageCell_ReuseId];
        if(!cell){
            cell = [[TCallCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TCallMessageCell_ReuseId];
            cell.delegate = self;
        }
    }
    else if([data isKindOfClass:[TLocationCellData class]]){
        cell = [tableView dequeueReusableCellWithIdentifier:TLocationMessageCell_ReuseId];
        if(!cell){
            cell = [[TLocationCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TLocationMessageCell_ReuseId];
            cell.delegate = self;
        }
    }
    else if([data isKindOfClass:[TGoodsCellData class]]){
        cell = [tableView dequeueReusableCellWithIdentifier:TGoodsMessageCell_ReuseId];
        if(!cell){
            cell = [[TGoodsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TGoodsMessageCell_ReuseId];
            cell.delegate = self;
        }
    }
    
    [cell setData:data];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}

- (void)scrollToBottom:(BOOL)animate
{
    if (_uiMsgs.count > 0) {
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:_uiMsgs.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:animate];
    }
}

- (void)didTapViewController
{
    if(_delegate && [_delegate respondsToSelector:@selector(didTapInMessageController:)]){
        [_delegate didTapInMessageController:self];
    }
}
- (void)sendMessage:(TMessageCellData *)msg
{
    [self.tableView beginUpdates];
    V2TIMMessage *imMsg = nil;
    TMessageCellData *dateMsg = nil;
    if(msg.custom){
        //如果是重发
        msg.status = Msg_Status_Sending;
        imMsg = msg.custom;
        dateMsg = [self transSystemMsgFromDate:[NSDate date]];
        NSInteger row = [_uiMsgs indexOfObject:msg];
        [_heightCache removeObjectAtIndex:row];
        [_uiMsgs removeObjectAtIndex:row];
        [self.tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:row inSection:0]]
                              withRowAnimation:UITableViewRowAnimationFade];
    }
    else{
        //新消息
        imMsg = [[YBImManager shareInstance]transIMMsgFromUIMsg:msg];//[self transIMMsgFromUIMsg:msg];
        dateMsg = [self transSystemMsgFromDate:imMsg.timestamp];
    }
    
    if(dateMsg){
        _msgForDate = imMsg;
        [_uiMsgs addObject:dateMsg];
        [self.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:_uiMsgs.count - 1 inSection:0]]
                              withRowAnimation:UITableViewRowAnimationFade];
    }
    msg.msgUiType = _msgUiType;
    msg.name = [Config getOwnNicename];
    if (_msgUiType == MsgUiType_Group) {
        msg.showName = YES;
    }else {
        msg.showName = NO;
    }
    [_uiMsgs addObject:msg];
    [self.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:_uiMsgs.count - 1 inSection:0]]
                          withRowAnimation:UITableViewRowAnimationFade];
    [self.tableView endUpdates];
    [self scrollToBottom:YES];
    
    __weak typeof(self) ws = self;
    
    [[YBImManager shareInstance]sendV2ImMsg:msg andReceiver:_conv.convId  complete:^(BOOL isSuccess, V2TIMMessage*sendMsg, NSString *desc) {
        if(isSuccess){
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"sendMsg----:%@",sendMsg.msgID);
                msg.custom =sendMsg;
                [ws changeMsg:msg status:Msg_Status_Succ];
               // [self.tableView reloadData];
                [self scrollToBottom:YES];
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                [ws changeMsg:msg status:Msg_Status_Fail];
            });

        }
    }];
    
    int delay = 1;
    if([msg isKindOfClass:[TImageMessageCellData class]]){
        delay = 0;
    }
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if(msg.status == Msg_Status_Sending){
//            [ws changeMsg:msg status:Msg_Status_Sending_2];
            [ws changeMsg:msg status:Msg_Status_Sending];

        }
    });
}

- (void)changeMsg:(TMessageCellData *)msg status:(TMsgStatus)status
{
    msg.status = status;
    NSInteger index = [_uiMsgs indexOfObject:msg];
    TMessageCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
    [cell setData:msg];
}

//- (TIMMessage *)transIMMsgFromUIMsg:(TMessageCellData *)data
//{
//    TIMMessage *msg = [[TIMMessage alloc] init];
//    data.userHeader = [Config getUserAvatar];
//    if([data isKindOfClass:[TTextMessageCellData class]]){
//        TIMTextElem *imText = [[TIMTextElem alloc] init];
//        TTextMessageCellData *text = (TTextMessageCellData *)data;
//        imText.text = text.content;
//        [msg addElem:imText];
//    }
//    else if([data isKindOfClass:[TFaceMessageCellData class]]){
//        TIMFaceElem *imImage = [[TIMFaceElem alloc] init];
//        TFaceMessageCellData *image = (TFaceMessageCellData *)data;
//        imImage.index = (int)image.groupIndex;
//        imImage.data = [image.faceName dataUsingEncoding:NSUTF8StringEncoding];
//        [msg addElem:imImage];
//    }
//    else if([data isKindOfClass:[TImageMessageCellData class]]){
//        TIMImageElem *imImage = [[TIMImageElem alloc] init];
//        TImageMessageCellData *uiImage = (TImageMessageCellData *)data;
//        imImage.path = uiImage.path;
//        [msg addElem:imImage];
//    }
//    else if([data isKindOfClass:[TVideoMessageCellData class]]){
//        TIMVideoElem *imVideo = [[TIMVideoElem alloc] init];
//        TVideoMessageCellData *uiVideo = (TVideoMessageCellData *)data;
//        imVideo.videoPath = uiVideo.videoPath;
//        imVideo.snapshotPath = uiVideo.snapshotPath;
//        imVideo.snapshot = [[TIMSnapshot alloc] init];
//        imVideo.snapshot.width = uiVideo.snapshotItem.size.width;
//        imVideo.snapshot.height = uiVideo.snapshotItem.size.height;
//        imVideo.video = [[TIMVideo alloc] init];
//        imVideo.video.duration = (int)uiVideo.videoItem.duration;
//        imVideo.video.type = uiVideo.videoItem.type;
//        [msg addElem:imVideo];
//    }
//    else if([data isKindOfClass:[TVoiceMessageCellData class]]){
//        TIMSoundElem *imSound = [[TIMSoundElem alloc] init];
//        TVoiceMessageCellData *uiSound = (TVoiceMessageCellData *)data;
//        imSound.path = uiSound.path;
//        imSound.second = uiSound.duration;
//        imSound.dataSize = uiSound.length;
//        [msg addElem:imSound];
//    }
//    else if([data isKindOfClass:[TFileMessageCellData class]]){
//        TIMFileElem *imFile = [[TIMFileElem alloc] init];
//        TFileMessageCellData *uiFile = (TFileMessageCellData *)data;
//        imFile.path = uiFile.path;
//        imFile.fileSize = uiFile.length;
//        imFile.filename = uiFile.fileName;
//        [msg addElem:imFile];
//    }
//    else if([data isKindOfClass:[TGiftMessageCellData class]]){
//        TIMCustomElem *imFile = [[TIMCustomElem alloc] init];
//        TGiftMessageCellData *gift = (TGiftMessageCellData *)data;
//        imFile.data = gift.data;
//
//        [msg addElem:imFile];
//    }
//    else if([data isKindOfClass:[TGoodsCellData class]]){
//        TIMCustomElem *imFile = [[TIMCustomElem alloc] init];
//        TGoodsCellData *imGoods = (TGoodsCellData *)data;
//        imFile.data = imGoods.data;
//        [msg addElem:imFile];
//    }
//    else if ([data isKindOfClass:[TLocationCellData class]]){
//        TIMLocationElem *imLocation = [[TIMLocationElem alloc]init];
//        TLocationCellData *locData = (TLocationCellData *)data;
//        imLocation.desc = locData.locDes;
//        imLocation.latitude = locData.lat;
//        imLocation.longitude = locData.lng;
//        [msg addElem:imLocation];
//    }
//    data.custom = msg;
//    return msg;
//
//}
- (TMessageCellData *)transSystemMsgFromDate:(NSDate *)date
{
    if(_msgForDate == nil || [date timeIntervalSinceDate:_msgForDate.timestamp] > 5 * 60){
        TSystemMessageCellData *system = [[TSystemMessageCellData alloc] init];
        system.content = [PublicObj getDateDisplayString:date];
        system.timestamp = date;
        return system;
    }
    return nil;
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if(!_noMoreMsg && scrollView.contentOffset.y <= TMessageController_Header_Height){
        if(!_headerView.isAnimating){
            [_headerView startAnimating];
        }
    }
    else{
        if(_headerView.isAnimating){
            [_headerView stopAnimating];
        }
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if(scrollView.contentOffset.y <= TMessageController_Header_Height){
        [self loadMessage];
    }
}

#pragma mark - message cell delegate
- (void)needReloadMessage:(TMessageCellData *)data
{
    NSInteger index = [_uiMsgs indexOfObject:data];
    [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:index inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
}

- (void)didSelectMessage:(TMessageCellData *)data
{
    if([data isKindOfClass:[TVoiceMessageCellData class]]){
        TVoiceMessageCellData *voice = (TVoiceMessageCellData *)data;
        [self playVoiceMessage:voice];
    }
    else if([data isKindOfClass:[TImageMessageCellData class]]){
        if(_delegate && [_delegate respondsToSelector:@selector(messageController:didSelectMessages:atIndex:)]){
            NSInteger index = [_uiMsgs indexOfObject:data];
            [_delegate messageController:self didSelectMessages:_uiMsgs atIndex:index];
        }
    }
}
#pragma mark === 点击头像=====
-(void)didTapHeaderMessage:(TMessageCellData *)data{
    V2TIMMessage *imMsg = data.custom;
    if(imMsg == nil || imMsg.isSelf || _uiFrom == UiFrom_Samll){
        return;
    }
    YBCenterVC *center = [[YBCenterVC alloc]init];
    center.otherUid = data.senderUid;
    center.isPush = YES;
    [[YBBaseAppDelegate sharedAppDelegate] pushViewController:center animated:YES];
}

- (void)didLongPressMessage:(TMessageCellData *)data inView:(UIView *)view
{
    int type = 0;
    int dration = 0;
    if([data isKindOfClass:[TTextMessageCellData class]] && data.isSelf){
        type = 0;
  
    }else if([data isKindOfClass:[TTextMessageCellData class]] && !data.isSelf){
        type = 1;
  
    }else if([data isKindOfClass:[TVoiceMessageCellData class]] && data.isSelf){
           
        dration = 30;
        type = 2;
        
    }else if([data isKindOfClass:[TImageMessageCellData class]] && data.isSelf){
        
        type = 2;
        
    }
    else{
        return;
    }
    
    _menuUIMsg = data;
    UIWindow * window=[[[UIApplication sharedApplication] delegate] window];

    CGRect rect=[view convertRect: view.bounds toView:window];
    YBWeakSelf;
    chatalertview = [[TChatAlertView alloc] initWithFrame:CGRectMake(0, 0, _window_width, _window_height) andScreenFrame:rect andtype:type anddration:dration];
    chatalertview.block = ^(int code) {
        [weakSelf mysendclick:code];
    };
    [[UIApplication sharedApplication].delegate.window addSubview:chatalertview];
}
-(void)mysendclick:(int)code{
    [chatalertview removeFromSuperview];
    chatalertview = nil;
    if (code == 0) {
        [self onCopy];
    }else if (code == 1){
        [self onRevoke];
    }
}
- (void)didReSendMessage:(TMessageCellData *)data {
    _reSendUIMsg = data;
    YBWeakSelf;
    NSDictionary *contentDic = @{@"title":@"",@"msg":YZMsg(@"确定重发此消息吗？"),@"left":YZMsg(@"取消"),@"right":YZMsg(@"确定")};
    [YBAlertView showAlertView:contentDic complete:^(int eventType) {
        if (eventType == 1) {
            [weakSelf sendMessage:_reSendUIMsg];
        }
    }];
    
    
}

#pragma mark ===复制====
-(void)onCopy{
    if([_menuUIMsg isKindOfClass:[TTextMessageCellData class]]){
        TTextMessageCellData *text = (TTextMessageCellData *)_menuUIMsg;
        UIPasteboard *paste = [UIPasteboard generalPasteboard];
        paste.string = text.content;
        [MBProgressHUD showError:YZMsg(@"复制成功")];
    }
  
}
#pragma mark ===撤回====
- (void)onRevoke {
    V2TIMMessage *imMsg = _menuUIMsg.custom;
    if(imMsg == nil){
        return;
    }
    NSInteger index = [_uiMsgs indexOfObject:_menuUIMsg];
    if (index == NSNotFound) {
        NSLog(@"s没有没有没有没有没有");
        return;
    }
    NSLog(@"sdasdjahsjd-----:%ld",index);

    if([[NSDate date] timeIntervalSinceDate:imMsg.timestamp] > 2 * 60){
        [MBProgressHUD showError:YZMsg(@"该消息发送时间已超过两分钟,无法撤回")];
        return;
    }
    __weak typeof(self) ws = self;
    [[V2TIMManager sharedInstance] revokeMessage:_menuUIMsg.custom
                                            succ:^{
        // 撤回消息成功
        dispatch_async(dispatch_get_main_queue(), ^{
           [ws revokeMsg:ws.menuUIMsg];
            NSLog(@"imManagerrevokeTime---:%@ \n id:%@",imMsg.timestamp,imMsg.msgID);

        });

    } fail:^(int code, NSString *msg) {
        // 撤回消息失败
        NSLog(@"intcode===%d==%@",code,msg);
        NSLog(@"imManagerrevokeTime---:%@ \n id:%@",imMsg.timestamp,imMsg.msgID);

    }];
}

- (void)revokeMsg:(TMessageCellData *)msg{
    
    V2TIMMessage *imMsg = msg.custom;
    if(imMsg == nil){
        return;
    }

    [self.tableView beginUpdates];
    NSInteger index = [_uiMsgs indexOfObject:msg];
    [_heightCache removeObjectAtIndex:index];
    [_uiMsgs removeObject:msg];
    [self.tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:index inSection:0]] withRowAnimation:UITableViewRowAnimationFade];

    TSystemMessageCellData *data = [[TSystemMessageCellData alloc] init];
    data.timestamp = msg.timestamp;
    data.msgUiType = _msgUiType;
    if(imMsg.isSelf){
        data.content = YZMsg(@"你撤回了一条消息");
    }
    else{
        data.content = YZMsg(@"对方撤回了一条消息");
    }
    [_uiMsgs insertObject:data atIndex:index];
    [self.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:index inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
    [self.tableView endUpdates];
    [self scrollToBottom:YES];
}


- (void)sendImageMessage:(UIImage *)image andIndex:(int)index;{
    NSData *data = UIImagePNGRepresentation(image);
    NSString *path = [TUIKit_Image_Path stringByAppendingString:[THelper genImageName:[NSString stringWithFormat:@"%d",index]]];
    [[NSFileManager defaultManager] createFileAtPath:path contents:data attributes:nil];
    
    TImageMessageCellData *uiImage = [[TImageMessageCellData alloc] init];
    uiImage.path = path;
    uiImage.length = data.length;
    uiImage.head = TUIKitResource(@"default_head");
    uiImage.isSelf = YES;
    uiImage.uploadProgress = 0;
    [self sendMessage:uiImage];
}

- (void)sendVideoMessage:(NSURL *)url{
    NSData *videoData = [NSData dataWithContentsOfURL:url];
    NSString *videoPath = [NSString stringWithFormat:@"%@%@.%@", TUIKit_Video_Path, [THelper genVideoName:nil], url.pathExtension];
    [[NSFileManager defaultManager] createFileAtPath:videoPath contents:videoData attributes:nil];
    
    NSDictionary *opts = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
    AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:url options:opts];
    NSInteger duration = (NSInteger)urlAsset.duration.value / urlAsset.duration.timescale;
    AVAssetImageGenerator *gen = [[AVAssetImageGenerator alloc] initWithAsset:urlAsset];
    gen.appliesPreferredTrackTransform = YES;
    gen.maximumSize = CGSizeMake(192, 192);
    NSError *error = nil;
    CMTime actualTime;
    CMTime time = CMTimeMakeWithSeconds(0.0, 10);
    CGImageRef imageRef = [gen copyCGImageAtTime:time actualTime:&actualTime error:&error];
    UIImage *image = [[UIImage alloc] initWithCGImage:imageRef];
    CGImageRelease(imageRef);
    
    NSData *imageData = UIImagePNGRepresentation(image);
    NSString *imagePath = [TUIKit_Video_Path stringByAppendingString:[THelper genSnapshotName:nil]];
    [[NSFileManager defaultManager] createFileAtPath:imagePath contents:imageData attributes:nil];
    
    TVideoMessageCellData *uiVideo = [[TVideoMessageCellData alloc] init];
    uiVideo.snapshotPath = imagePath;
    uiVideo.snapshotItem = [[TSnapshotItem alloc] init];
    UIImage *snapshot = [UIImage imageWithContentsOfFile:imagePath];
    uiVideo.snapshotItem.size = snapshot.size;
    uiVideo.snapshotItem.length = imageData.length;
    uiVideo.videoPath = videoPath;
    uiVideo.videoItem = [[TVideoItem alloc] init];
    uiVideo.videoItem.duration = duration;
    uiVideo.videoItem.length = videoData.length;
    uiVideo.videoItem.type = url.pathExtension;
    uiVideo.head = TUIKitResource(@"default_head");
    uiVideo.isSelf = YES;
    uiVideo.uploadProgress = 0;
    [self sendMessage:uiVideo];
}

- (void)sendFileMessage:(NSURL *)url
{
    [url startAccessingSecurityScopedResource];
    NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] init];
    NSError *error;
    __weak typeof(self) ws = self;
    [coordinator coordinateReadingItemAtURL:url options:0 error:&error byAccessor:^(NSURL *newURL) {
        NSData *fileData = [NSData dataWithContentsOfURL:url];
        NSString *fileName = [url lastPathComponent];
        NSString *filePath = [TUIKit_File_Path stringByAppendingString:fileName];
        [[NSFileManager defaultManager] createFileAtPath:filePath contents:fileData attributes:nil];
        if([[NSFileManager defaultManager] fileExistsAtPath:filePath]){
            long fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil] fileSize];
            TFileMessageCellData *uiFile = [[TFileMessageCellData alloc] init];
            uiFile.path = filePath;
            uiFile.fileName = fileName;
            uiFile.length = (int)fileSize;
            uiFile.head = TUIKitResource(@"default_head");
            uiFile.isSelf = YES;
            uiFile.uploadProgress = 0;
            [ws sendMessage:uiFile];
        }
    }];
    [url stopAccessingSecurityScopedResource];
}
- (void)sendCustomMessage:(NSDictionary *)dic{
//    TGiftMessageCellData *gift = [[TGiftMessageCellData alloc] init];
//    gift.giftIcon = strFormat([dic valueForKey:@"gifticon"]);
//    gift.giftNum = strFormat([dic valueForKey:@"giftcount"]);
//    gift.giftName = strFormat([dic valueForKey:@"giftname"]);
//    gift.data = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
//    gift.isSelf = YES;
//    [self.tableView beginUpdates];
//    TIMMessage *imMsg = nil;
//    TMessageCellData *dateMsg = nil;
//        //新消息
//        imMsg = [self transIMMsgFromUIMsg:gift];
//        dateMsg = [self transSystemMsgFromDate:imMsg.timestamp];
//    
//    if(dateMsg){
//        _msgForDate = imMsg;
//        [_uiMsgs addObject:dateMsg];
//        [self.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:_uiMsgs.count - 1 inSection:0]]
//                              withRowAnimation:UITableViewRowAnimationFade];
//    }
//    [_uiMsgs addObject:gift];
//    [self.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:_uiMsgs.count - 1 inSection:0]]
//                          withRowAnimation:UITableViewRowAnimationFade];
//    [self.tableView endUpdates];
//    [self scrollToBottom:YES];


}

- (void)playVoiceMessage:(TVoiceMessageCellData *)voice
{
    __weak typeof(self) ws = self;
    void (^playBlock)(NSString *path) = ^(NSString *path){
        //update view
        NSInteger row = [ws.uiMsgs indexOfObject:voice];
        [ws.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:row inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
        //play current
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
        NSURL *url;
        NSString *removePath;
        if ([EMVoiceConverter isAMRFile:path]){
//        if (voice.isSelf) {
            NSString *wavPath = [[path stringByDeletingPathExtension] stringByAppendingString:@".wav"];
            [THelper convertAmr:path toWav:wavPath];
            removePath = wavPath;
            url = [NSURL fileURLWithPath:wavPath];
        }else{
            removePath = path;
            url = [NSURL fileURLWithPath:path];
        }
        _voicePlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
        [_voicePlayer play];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(voice.duration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [[NSFileManager defaultManager] removeItemAtPath:removePath error:nil];
            voice.isPlaying = NO;
            NSInteger row = [ws.uiMsgs indexOfObject:voice];
            [ws.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:row inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
        });
    };
    

    //stop play
    if([_voicePlayer isPlaying]){
        [_voicePlayer stop];
    }
    
    //update data
    for (NSInteger index = 0; index < _uiMsgs.count; ++index) {
        if(![_uiMsgs[index] isKindOfClass:[TVoiceMessageCellData class]]){
            continue;
        }
        TVoiceMessageCellData *uiMsg = _uiMsgs[index];
        if(uiMsg == voice){
            uiMsg.isPlaying = !uiMsg.isPlaying;
        }
        else{
            uiMsg.isPlaying = NO;
        }
    }
    
    if(voice.isPlaying){
        BOOL isExist = NO;
        NSString *path = [voice getVoicePath:&isExist];
        if(isExist){
            playBlock(path);
        }
        else{
            [voice downloadVoice:^(NSInteger curSize, NSInteger totalSize) {
            } response:^(int code, NSString *desc, NSString *path) {
                if(code == 0){
                    playBlock(path);
                }
            }];
        }
    }
    else{
        //update view
        NSInteger row = [ws.uiMsgs indexOfObject:voice];
        [ws.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:row inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
    }
    
    
}
/// 粗略获取发送条数
-(int)sendMsgNums;{
    NSMutableArray *countA = [NSMutableArray array];
    for (int i = 0; i<_uiMsgs.count; i++) {
        TMessageCellData *data = _uiMsgs[i];
        //NSLog(@"rk_===>%@",data.senderUid);
        if ([data.senderUid isEqual:[Config getOwnID]] || data.isSelf) {
            [countA addObject:data];
        }
    }
    //NSLog(@"rk_===>count:%d",(int)countA.count);
    return (int)countA.count;
}
@end
